package com.guigu.controller;

import com.guigu.vo.Result;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/FileUpload")
public class FileUploadController {
    // 文件上传保存路径
    private static final String filePath = System.getProperty("user.dir") + "/file/";
    @PostMapping("/saveFile")
    @ResponseBody
    public Result saveFile(@RequestParam("file") MultipartFile file) {

        String flag;
        synchronized (FollowUpDiaryController.class) {
            // 获取时间戳
            flag = System.currentTimeMillis() + "";
            // 获取原始文件名
            String fileName = file.getOriginalFilename();
            try {
                // 创建目录
                File directory = new File(filePath);
                if (!directory.exists()) {
                    directory.mkdirs();
                }
                // 文件存储形式: 时间戳-文件名
                FileUtils.writeByteArrayToFile(new File(filePath + flag + "-" + fileName), file.getBytes());
                System.out.println("文件上传成功");
                Thread.sleep(1000);
            } catch (Exception e) {
                System.err.println(fileName + "--文件上传失败");
                e.printStackTrace();
            }
        }

        return new Result<>("200", "true", "保存成功", flag);
    }

    //文件下载
    @GetMapping("/downFile/{flag}")
    @ResponseBody
    public Result downFile(@PathVariable String flag, HttpServletResponse response) {
        File file = new File(filePath);
        if (!file.isDirectory()) {
            file.mkdirs();
        }

        List<String> fileNames = Arrays.asList(file.list());
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");

        try {
            if (StringUtils.isNotBlank(avatar)) {
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtils.readFileToByteArray(new File(filePath + avatar));

                OutputStream os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>("200", "flash", "文件下载失败", "");
        }
        return new Result<>("200", "true", "文件下载成功", "");
    }
}
